<template>
  <div>
    <div>
      <FormPanel ref="partSale" :list="partsPurchaseList" :cols="3" labelWidth="100" formType="add" :isSubmitBtn="false" @formChange="partsPurchaseChange" />
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog1">关 闭</el-button>
      <AjaxButton :click="saveDialog" type="primary">出 售</AjaxButton>
    </div>
  </div>
</template>

<script>
import { saveOrder, getDealerInfo, getDealerCompanyByCode, queryStockAge } from '@/api/part/exchange/platform';
import { isNullOrUndefined } from 'util';
import { dictionary } from '@/utils/dictMixin';
import { IDNumber, phone, numberCheck, email } from '@/utils/validate';
import moment from 'moment';
export default {
  name: 'exchangePartSale',
  components: {},
  mixins: [dictionary],
  props: {
    partsInfos: {
      type: Object
    },
    saveData: {
      type: Object
    }
  },

  data() {
    this.saveOrderInfo = {};
    return {
      partsPurchaseList: this.createPurchaseformList(),
      clickType: this.partsInfos.details,
      totalPrices: '',
      purchaseNum: 0,
      dealerInfo: {},
      provienceList: [], // 省份列表
      // partsSaleInfoChange:
      stockAge: '' // 库龄
    };
  },
  computed: {
    calculate() {
      return this.partsPurchaseList.find(item => item.fieldName == 'quantity').initialValue * this.partsPurchaseList.find(item => item.fieldName == 'inOutTaxedPrice').initialValue;
    }
  },
  watch: {
    calculate(newVal, oldVal) {
      this.partsPurchaseList.find(item => item.fieldName == 'totolPrice').initialValue = Number(newVal).toFixed(2);
    }
  },
  created() {
    this.getInitialVal();
    this.provienceList = this.createDictRegion();
    this.createdRegion();
  },

  methods: {
    // 创建省份城市
    async createdRegion() {
      let res = await getDealerCompanyByCode({ ownerCode: this.saveData.ownerCode });
      this.dealerInfo = res.data;
      this.partsPurchaseList.forEach(element => {
        if (element.fieldName == 'provinceId') {
          element.initialValue = res.data['provinceId'] + '';
          this.partsPurchaseList.find(item => item.fieldName == 'cityId').itemList = this.provienceList.find(item => item.value == element.initialValue).children;
        }
        if (element.fieldName == 'cityId') {
          element.initialValue = res.data['cityId'] + '';
        }
      });
    },
    async getInitialVal() {
      // console.log('求购信息', this.saveData);
      this.partsPurchaseList.forEach(element => {
        if (element.fieldName == 'regionCode') {
          element.itemList = [{ text: this.saveData.dealerRegionName, value: this.saveData.dealerRegionCode }];
          element.initialValue = this.saveData.dealerRegionCode;
        }
        if (element.fieldName == 'areaCode') {
          element.itemList = [{ text: this.saveData.dealerAreaName, value: this.saveData.dealerAreaCode }];
          element.initialValue = this.saveData.dealerAreaCode;
        }
      });
      // 获取当前经销商基本信息
      try {
        let res = await getDealerCompanyByCode();
        this.dealerInfo = res.data;
        if (res.resultCode == 200) {
          this.partsPurchaseList.find(item => item.fieldName == 'sAddr').initialValue = this.dealerInfo.address;
          this.partsPurchaseList.find(item => item.fieldName == 'sContacts').initialValue = this.dealerInfo.linkMan;
          this.partsPurchaseList.find(item => item.fieldName == 'sTel').initialValue = this.dealerInfo.phone;
        }
      } catch (error) {
        this.$notify.error({ title: '提示信息', message: '请手动输入联系人信息' });
      }
      // 查询库龄
      try {
        let ownerCode = this.saveData.ownerCode;
        let partNo = this.saveData.partNo;
        let storageCode = this.saveData.storageCode;
        let stockRes = await queryStockAge({ ownerCode, partNo, storageCode });
        if (stockRes.resultCode == 200) {
          if (stockRes.data.rows.length) {
            this.stockAge = moment(stockRes.data.rows[0].stockAgeTime);
            // console.log(this.stockAge, '时间');
          }
        }
      } catch (error) {}
    },
    // 点击按钮
    async saveDialog() {
      this.$refs.partSale.SUBMIT_FORM();
      let [err, formData] = await this.$refs.partSale.GET_FORM_DATA();
      // console.log(err, 342442);
      if (err) {
        return this.$notify.warning({ title: '提示信息', message: '请检查必填项' });
      }
      // console.log('saveDialog:', this.saveOrderInfo);
      this.saveOrderInfo.sOwnerCode = this.dealerInfo.companyCode;
      this.saveOrderInfo.sOwnerName = this.dealerInfo.dealerName;
      let dateTemp = moment().diff(this.stockAge, 'day');
      // console.log(dateTemp, '时间差');

      let res = await saveOrder({ ...this.saveData, ...this.saveOrderInfo, stockAge: dateTemp });
      if (res.resultCode === 200) {
        // console.log('res', res.resultCode, res.success, res.data);
        if (!res.success) {
          this.closeDialog1(false, 'refresh');
          return this.$notify({
            title: '提示信息',
            message: res.data.message,
            type: 'error'
          });
        }
        this.closeDialog(false, 'refresh');
        return this.$notify({
          title: '提示信息',
          message: '成功发布订单',
          type: 'success'
        });
        this.closeDialog(false, 'refresh');
      }
    },
    closeDialog1(val, type) {
      this.$emit('close');
    },
    // 点击关闭按钮
    closeDialog(val, type) {
      this.$emit('close', val, type);
    },
    // 表单提交
    partsPurchaseChange(val) {
      this.saveOrderInfo = val;
    },
    // 创建求购信息
    createPurchaseformList() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '求购信息',
          style: {}
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'bOwnerCode',
          placeholder: '',
          initialValue: this.saveData.ownerCode,
          // itemList: [{ text: '原厂库', value: '1' }],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          // 库没找到
          fieldName: 'bOwnerName',
          disabled: true,
          placeholder: '',
          initialValue: this.saveData.dearlerName,
          // itemList: [{ text: '原厂库', value: '1' }],
          selfCols: 2
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          disabled: true,
          placeholder: '',
          initialValue: this.saveData.partNo
          // itemList: [{ text: '原厂库', value: '1' }],
        },
        {
          type: 'INPUT',
          label: '配件名称',
          disabled: true,
          fieldName: 'partName',
          placeholder: '',
          initialValue: this.saveData.partName
          // itemList: [{ text: '原厂库', value: '1' }],
        },
        {
          type: 'SELECT',
          label: '快递方式',
          disabled: true,
          fieldName: 'expressType',
          placeholder: '',
          initialValue: this.saveData.expressType,
          itemList: this.createDictList('8114')
        },
        {
          type: 'SELECT',
          label: '大区',
          fieldName: 'regionCode',
          disabled: true,
          placeholder: '',
          itemList: [],
          initialValue: this.saveData.regionCode
          // itemList: [{ text: '原厂库', value: '1' }],
        },
        {
          type: 'SELECT',
          label: '小区',
          fieldName: 'areaCode',
          disabled: true,
          placeholder: '',
          itemList: [],
          initialValue: this.saveData.areaCode
        },
        {
          type: 'SELECT',
          label: '省份',
          fieldName: 'provinceId',
          disabled: true,
          itemList: this.createDictRegion(),
          placeholder: '',
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '城市',
          fieldName: 'cityId',
          disabled: true,
          itemList: [],
          placeholder: '',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '联系地址',
          fieldName: 'bAddr',
          disabled: true,
          placeholder: '',
          initialValue: this.saveData.contactorAddress,
          // itemList: [{ text: '原厂库', value: '1' }],
          selfCols: 2
        },
        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'bContacts',
          disabled: true,
          placeholder: '',
          initialValue: this.saveData.contacts
          // itemList: [{ text: '原厂库', value: '1' }],
        },
        {
          type: 'INPUT',
          label: '联系电话',
          disabled: true,
          fieldName: 'bTel',
          placeholder: '',
          initialValue: this.saveData.contactorMobile
          // itemList: [{ text: '原厂库', value: '1' }],
        },
        {
          type: 'DATE',
          label: '到期日期',
          disabled: true,
          fieldName: 'endDate',
          initialValue: this.saveData.endDate
          // itemList: [{ text: '原厂库', value: '1' }],
        },
        {
          type: 'INPUT_NUMBER',
          label: '含税购买单价',
          precision: 2,
          disabled: true,
          fieldName: 'inOutTaxedPrice',
          placeholder: '',
          initialValue: this.saveData.inOutTaxedPrice
          // itemList: [{ text: '原厂库', value: '1' }],
        },
        {
          type: 'INPUT_NUMBER',
          // 剩余数量
          label: '求购数量',
          precision: 2,
          disabled: true,
          fieldName: 'remainingQuantity',
          placeholder: '',
          initialValue: this.saveData.remainingQuantity
          // itemList: [{ text: '原厂库', value: '1' }],
          // readonly: true
        },
        {
          type: 'BREAK_SPACE',
          label: '出售信息',
          style: {}
        },
        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'sContacts',
          placeholder: '',
          initialValue: '',
          rules: [{ required: true, message: '请输入联系人', trigger: 'blur' }]
          // itemList: [{ text: '原厂库', value: '1' }],
        },
        {
          type: 'INPUT',
          label: '联系电话',
          fieldName: 'sTel',
          placeholder: '',
          initialValue: '',
          rules: [
            { required: true, message: '请输入联系电话', trigger: 'blur' }
            // { trigger: 'blur', validator: phone }
          ]
          // itemList: [{ text: '原厂库', value: '1' }],
        },
        {
          type: 'INPUT_NUMBER',
          label: '出售数量',
          precision: 2,
          fieldName: 'quantity',
          min: 0.01,
          placeholder: '',
          initialValue: '',
          rules: [
            { required: true, message: '请输入出售数量', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                if (value > this.saveData.remainingQuantity) {
                  return callback(new Error('出售数量不能大于求购数量'));
                } else {
                  callback();
                }
              },
              trigger: 'change'
            },
            {
              validator: (rule, value, callback) => {
                if (value > 0) {
                  callback();
                } else {
                  callback(new Error('出售数量不能为0'));
                }
              },
              trigger: ['blur', 'change']
            }
          ]
        },
        {
          type: 'INPUT',
          label: '联系地址',
          fieldName: 'sAddr',
          placeholder: '',
          initialValue: '',
          rules: [{ required: true, message: '请输入联系地址', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '合计金额',
          fieldName: 'totolPrice',
          precision: 2,
          placeholder: '',
          initialValue: '',
          readonly: true
        }
      ];
    }
  }
};
</script>

<style></style>
